﻿/*************************************************************************
 *
 * Copyright (c) 2009-2015 Xuld. All rights reserved.
 * 
 * Project Url: http://work.xuld.net/circus
 * 
 * This source code is part of the Project Circus.
 * 
 * This code is licensed under The Circus License.
 * See the file License.html for the license details.
 * 
 * 
 * You must not remove this notice, or any other, from this software.
 *
 * 
 *************************************************************************/


using System;
using System.Reflection;
using System.ComponentModel;

namespace Circus.Utility {

    /// <summary>
    /// 提供枚举操作的辅助方法。
    /// </summary>
    public static class EnumHelper {

        /// <summary>
        /// 获取和一个枚举值关联的 <see cref="DescriptionAttribute"/> 属性。
        /// </summary>
        /// <param name="enumeration">要获取信息的 <see cref="Enum"/> 对象。</param>
        /// <returns>一个字符串，由 <see cref="DescriptionAttribute"/> 指定的信息。如果不存在对应的 <see cref="DescriptionAttribute"/>，则返回 null 。</returns>
        public static string getDescription(this Enum enumeration) {
            Type type = enumeration.GetType();
            MemberInfo[] memInfo = type.GetMember(enumeration.ToString());

            if(null != memInfo && memInfo.Length > 0) {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if(null != attrs && attrs.Length > 0)
                    return ((DescriptionAttribute)attrs[0]).Description;
            }
            
            return enumeration.ToString();
        }
    }
}
